package com.pzhu.gmall.item.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.pzhu.gmall.bean.PmsProductSaleAttr;
import com.pzhu.gmall.bean.PmsSkuInfo;
import com.pzhu.gmall.bean.SkuHash;
import com.pzhu.gmall.service.SkuInfoService;
import com.pzhu.gmall.service.SpuService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 刘鹏 liupeng
 * @date 2019/11/2
 **/
@CrossOrigin
@Controller
public class ItemController {
    @Reference
    private SkuInfoService skuInfoService;

    @Reference
    private SpuService spuService;

    @RequestMapping("/index")
    public String index(ModelMap modelMap) {
        modelMap.put("hello", "hello world");
        String ts = "循环数据";
        List strings = new ArrayList(5);
        for (int i = 0; i < 5; i++) {
            strings.add(ts + i);
        }
        modelMap.put("strings", strings);
        modelMap.put("checked", 0);
        return "index";
    }

    @RequestMapping("{itemId}.html")
    public String item(@PathVariable("itemId") String itemId, ModelMap modelMap) throws InterruptedException {
        PmsSkuInfo skuInfo = skuInfoService.getSkuByItemId(itemId);
        modelMap.put("skuInfo", skuInfo);
        List<PmsProductSaleAttr> productSaleAttrs = spuService.getSpuSaleAttribute(skuInfo.getProductId(), itemId);
        modelMap.put("spuSaleAttrListCheckBySku", productSaleAttrs);
        //查询当前spu的hash结合
        List<SkuHash> skuHash = spuService.getSkuSHash(skuInfo.getProductId());
        List<Map> list = new ArrayList<>(skuHash.size());
        for (SkuHash hash : skuHash) {
            HashMap<Object, Object> skuHashMap = new HashMap<>();
            skuHashMap.put(hash.get("k"), hash.get("v"));
            list.add(skuHashMap);
        }
        String skuHashJsonStr = JSON.toJSONString(list);
        modelMap.put("skuHash", skuHashJsonStr);

        return "item";
    }

    @RequestMapping("/index2")
    @ResponseBody
    public String hello() {
        return "asdfassadasdSDFSDFDFASDFASD";
    }
}
